/***********************************************************************
	filename: 	DaterLinktoSQL.cpp
	created:	15/4/2012
	author:		4Ys
	
	purpose:	Implements a class of connection between C++ and mySQL
*************************************************************************/

#include "DaterlinktoSQL.h"
#include <string>
#include<iostream>
namespace Dater
{
	LinktoSQL::LinktoSQL(){}

	LinktoSQL::~LinktoSQL(){CloseMySQLConn();}

	int LinktoSQL::ConnMySQL(char* host, char* port, char* Db, char* user,
		char* passwd, char* charset, char* Msg)
	{
		if(mysql_init(&mysql) == NULL)
		{
			Msg = "Inital mysql handle error";
			return 1;
		}
		if(mysql_real_connect(&mysql,"127.0.0.1"/*host*/,user,passwd,Db,3306,NULL,0) == NULL)
		{
			Msg = "Failed to connect to database: Error";
			const char* error = mysql_error(&mysql);
			int errorno = mysql_errno(&mysql);
			return 1;
		}
		if(mysql_set_character_set(&mysql,"GBK") != 0)
		{
			Msg = "mysql_set_character_set Error";
			return 1;
		}

		return 0;
	}

	std::string LinktoSQL::SelectData(char* SQL, int Cnum, char* Msg, char rowDelimiter, char columnDelimiter)
	{
		MYSQL_ROW m_row;
		MYSQL_RES *m_res;
		char sql[2048];
		strcpy_s(sql, SQL);
		int rnum = 0;
		
		if(mysql_query(&mysql,sql) != 0)
		{
			Msg = "select ps_info Error";
			return "";
		}
		m_res = mysql_store_result(&mysql);
		//std::cout << "\nm_res:  " << m_res;

		if(m_res == NULL)
		{
			Msg = "select username Error";
			return "";
		}
		std::string str("");

		while(m_row = mysql_fetch_row(m_res))
		{
			if( rnum != 0)
				str += rowDelimiter;
			
			for(int i = 0; i < Cnum; i++)
			{
				if( i != 0)
					str += columnDelimiter;
				if(m_row[i])
					str += m_row[i];
			}

			rnum++;
		}

		mysql_free_result(m_res);
		return str;
	}

	int LinktoSQL::InsertData(char* SQL, char* Msg)
	{
		char sql[2048];
		sprintf_s(sql, SQL);
		if(mysql_query(&mysql,sql) != 0)
		{
			const char* error = mysql_error(&mysql);
			Msg = "Insert Data Error";
			return 1;
		}
		return 0;
	}

	int LinktoSQL::UpdateData(char* SQL, char* Msg)
	{
		char sql[2048];
		sprintf_s(sql, SQL);
		if(mysql_query(&mysql,sql) != 0)
		{
			Msg = "Update Data Error";
			return 1;
		}
		return 0;
	}

	int LinktoSQL::DeleteData(char* SQL, char* Msg)
	{
		char sql[2048];
		sprintf_s(sql, SQL);
		if(mysql_query(&mysql, sql) != 0)
		{
			Msg = "Delete Data Error";
			return 1;
		}
		return 0;
	}

	void LinktoSQL::CloseMySQLConn()
	{
		mysql_close(&mysql);
	}
}